package org.webrtc.yl.WebSocket;

import org.webrtc.yl.WebSocket.Listener.ClientWebSocketListener;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class AndroidWebSocketClient extends org.java_websocket.client.WebSocketClient {

    private ClientWebSocketListener webSocketListener;

    public AndroidWebSocketClient(URI serverUri, ClientWebSocketListener listener) {
        super(serverUri);
        this.webSocketListener = listener;
    }

    @Override
    public void onOpen(ServerHandshake handshakeData) {
        System.out.println("WebSocket 连接打开");
        if (webSocketListener != null) {
            webSocketListener.onOpen("WebSocket 连接打开");
        }
    }

    @Override
    public void onMessage(String message) {
        if (webSocketListener != null) {
            webSocketListener.onMessage(message);
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("WebSocket 连接关闭");
        if (webSocketListener != null) {
            webSocketListener.onClose("WebSocket 连接关闭");
        }

    }

    @Override
    public void onError(Exception ex) {
        System.out.println("WebSocket 出现错误: " + ex.getMessage());
        if (webSocketListener != null) {
            webSocketListener.onError("WebSocket 出现错误: " + ex.getMessage());
        }
    }

    public void sendMessage(String message) {
        WebSocket conn = getConnection();
        if (conn != null) {
            conn.send(message);
        }
    }
}
